﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using TuoiThoProject.DAL;

namespace TuoiThoProject.BLL
{
    public class CategoryBLL
    {
        NewsDataContext data = new NewsDataContext();
        public List<tblCategory> getAllCategories()
        {
            return (from c in data.tblCategories
                    select c).ToList();
        }

        public List<tblCategory> getCatgory_ById(int CategoryId)
        {
            return (from c in data.tblCategories
                    where c.nCategoryId == CategoryId
                    select c).ToList();
        }

        public List<tblCategory> getAllCategories_ByParentId(int ParentId)
        {
            List<tblCategory> list1 = (from c in data.tblCategories
                                       where c.nParentId == ParentId
                                       select c).ToList();
            foreach (tblCategory cat in list1)
            {
                List<tblCategory> list2 = getAllCategories_ByParentId(cat.nCategoryId);
                foreach (tblCategory cat2 in list2)
                {
                    list1.Add(cat2);
                }
            }

            return list1;
        }

        public List<tblCategory> getAllCategories_ById(int CategoryId)
        {
            tblCategory cat = data.tblCategories.SingleOrDefault(c => c.nCategoryId == CategoryId);

            List<tblCategory> list = this.getAllCategories_ByParentId(cat.nCategoryId);
            list.Add(cat);

            return list;
        }

        public void Insert(string Name, string Description, string Url, int ParentId)
        {
            tblCategory cat = new tblCategory();
            cat.cCategoryName = Name;
            cat.cCategoryDescription = Description;
            cat.cUrls = Url;
            cat.nParentId = ParentId;

            data.tblCategories.InsertOnSubmit(cat);
            data.SubmitChanges();
        }


        public void Update(int CategoryId, string Name, string Description, string Url, int ParentId)
        {
            tblCategory cat = data.tblCategories.SingleOrDefault(c => c.nCategoryId == CategoryId);
            cat.cCategoryName = Name;
            cat.cCategoryDescription = Description;
            cat.cUrls = Url;
            cat.nParentId = ParentId;

            data.SubmitChanges();
        }

        public void Delete(int CategoryId)
        {
            tblCategory cat = data.tblCategories.SingleOrDefault(c => c.nCategoryId == CategoryId);
            data.tblCategories.DeleteOnSubmit(cat);
            data.SubmitChanges();
        }
    }
}